package com.wuliang.generate.common.sharding.configs;

import com.wuliang.generate.common.sharding.factories.ShardingDataSourceBuilder;
import com.wuliang.generate.common.sharding.pool.DefaultShardingDataSourcePool;
import com.wuliang.generate.common.sharding.pool.ShardingDataSourcePool;
import com.wuliang.generate.common.sharding.properties.DataSourceConfigProperties;
import io.shardingjdbc.core.api.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableConfigurationProperties(DataSourceConfigProperties.class)
public class ShardingConfig {

    @Autowired
    private DataSourceConfigProperties dataSourceConfigProperties;

    @Bean
    public DataSource dataSource() {
        dataSourceConfigProperties.getDataSource().forEach((dataSourceName, dataSourceProperties) -> {
            List<String> tableNames = new ArrayList<>();
            ShardingDataSourceBuilder.createBuilder()
                    .keyword(dataSourceName)
                    .url(dataSourceProperties.getUrl())
                    .password(dataSourceProperties.getPassword())
                    .username(dataSourceProperties.getUsername())
                    .tableNamesInDatabase(tableNames)
                    .build();
        });
        try {
            return shardingDataSourcePool().initShardingDataSource();
        } catch (SQLException ignore) {
            ignore.printStackTrace();
        }
        return null;
    }

    @Bean
    public HintManager hintManager() {
        HintManager hintManager = HintManager.getInstance();
        hintManager.setDatabaseShardingValue(1);
        return hintManager;
    }

    @Bean
    public ShardingDataSourcePool shardingDataSourcePool() {
        return new DefaultShardingDataSourcePool();
    }

}
